package com.gqh.weather.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.constraints.NotNull;

import com.gqh.weather.auth.UserInfo;
import com.gqh.weather.auth.UserContext;
import com.gqh.weather.domain.dto.LoginResponse;
import com.gqh.weather.domain.dto.YjStInfo;
import com.gqh.weather.domain.dto.YuejuanExamInfoResponse;
import com.gqh.weather.domain.dto.YuejuanLoginRequest;
import com.gqh.weather.domain.dto.YuejuanScore;
import com.gqh.weather.exception.BusinessException;
import com.gqh.weather.exception.Result;
import com.gqh.weather.service.YuejuanService;

import cn.dev33.satoken.stp.StpUtil;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;

/**
 * 阅卷平台控制器
 */
@Slf4j
@RestController
@RequestMapping("/pingjia/zh/v1/yj")
public class YueJuanController {
    
    @Autowired
    private YuejuanService yuejuanService;

    /**
     * 阅卷老师账号密码登录
     *
     * @param request 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid YuejuanLoginRequest request) {
        log.info("阅卷老师登录，账号: {}, 角色: {}", request.getAccount(), request.getRole());
        
        try {
            // 参数校验
            String role = request.getRole();
            if (!"0".equals(role) && !"1".equals(role) && !"2".equals(role)) {
                return Result.error("角色参数不正确，必须为0(正评)、1(复评)或2(仲裁)");
            }
            
            // 调用服务层进行登录验证
            YuejuanService.YuejuanLoginResult loginResult = yuejuanService.login(
                request.getAccount(), 
                request.getPassword(), 
                request.getRole()
            );
            
            // 创建用户信息
            UserInfo userInfo = new UserInfo();
            userInfo.setUid(loginResult.getSubtaskInfo().getId() + 1000000); // 使用子任务ID作为用户ID
            userInfo.setAccount(request.getAccount());
            userInfo.setRole(Integer.parseInt(request.getRole())); // 角色：0正评 1复评 2仲裁
            userInfo.setType(loginResult.getQId());
            userInfo.setYuejuan(true);

            // 执行Sa-Token登录
            StpUtil.login(userInfo.getUid());
            
            // 存储用户信息到Session
            StpUtil.getSession().set("userInfo", userInfo);
            
            // 构建登录响应
            LoginResponse response = new LoginResponse();
            response.setAccess_token(StpUtil.getTokenValue());
            response.setRefresh_token(""); // 暂时保留字段，返回空字符串
            
            return Result.success(response);
        } catch (BusinessException e) {
            log.warn("登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("登录异常", e);
            return Result.error("登录失败，请稍后重试");
        }
    }
    
    /**
     * 获取考试详情
     *
     * @return 考试信息
     */
    @GetMapping("/exam_info")
    public Result<YuejuanExamInfoResponse> examInfo() {
        log.info("获取考试详情");
        
        try {
            // 获取当前用户信息
            UserInfo userInfo = UserContext.getUserInfo();
            if (userInfo == null) {
                return Result.error("用户未登录");
            }
            
            // 构造阅卷老师信息
            YjStInfo stInfo = new YjStInfo();
            stInfo.setAccount(userInfo.getAccount());
            stInfo.setRole(userInfo.getRole());
            stInfo.setSubtaskId(userInfo.getUid() - 1000000); // 还原子任务ID
            stInfo.setQid(userInfo.getType());
            
            // 调用服务层获取考试详情
            YuejuanExamInfoResponse examInfo = yuejuanService.examInfo(stInfo);
            
            return Result.success(examInfo);
        } catch (BusinessException e) {
            log.warn("获取考试详情失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取考试详情异常", e);
            return Result.error("获取考试详情失败，请稍后重试");
        }
    }
    
    /**
     * 打分提交
     *
     * @param studentId 学生ID
     * @param score 分数
     * @return 提交结果
     */
    @PostMapping("/score")
    public Result<Void> score(
            @RequestParam("student_id") @NotNull Integer studentId,
            @RequestParam("score") @NotNull String score) {
        log.info("打分提交，学生ID: {}, 分数: {}", studentId, score);
        
        try {
            // 获取当前用户信息
            UserInfo userInfo = UserContext.getUserInfo();
            if (userInfo == null) {
                return Result.error("用户未登录");
            }
            
            // 创建YuejuanScore对象
            YuejuanScore yuejuanScore = new YuejuanScore();
            yuejuanScore.setStudentId(studentId);
            yuejuanScore.setScore(score);
            
            // 调用服务层进行打分提交
            yuejuanService.score(
                userInfo.getUid() - 1000000, // 还原子任务ID
                userInfo.getType(), 
                userInfo.getRole(), 
                userInfo.getAccount(), 
                yuejuanScore
            );
            
            return Result.success(null);
        } catch (BusinessException e) {
            log.warn("打分提交失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("打分提交异常", e);
            return Result.error("打分提交失败，请稍后重试");
        }
    }
}